package com.eascs.accessory.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.accessory.dao.AccessoryDao;
import com.eascs.accessory.entity.Accessory;
import com.eascs.accessory.entity.O2oAccessoryProvince;
import com.eascs.accessory.form.AccessoryForm;
import com.eascs.accessory.service.AccessoryService;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oPlatformRegional;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.sys.SysResources;
import com.eascs.workflow.common.vo.ModelResult;

@Service
public class AccessoryServiceImpl implements AccessoryService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	AccessoryDao accessoryDao;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	@Override
	public PageResult<Object[]> findPageAccessory(AccessoryForm accessoryForm) {
		SqlPageQuery<Object[]> page = new SqlPageQuery<>(Object[].class, accessoryForm.getPageSize(), accessoryForm.getShowPage());
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT * FROM o2o_guideline");
		page.setQuerySql(sql.toString());
		PageResult<Object[]> data = accessoryDao.findDataWithPage(page);
		return data;
	}

	@Override
	public ModelResult<List<Accessory>> selectAccessoryList() {

		ModelResult<List<Accessory>> model = new ModelResult<List<Accessory>>();
		try {
			List<Accessory> list = accessoryDao.selectAccessoryList();
			model.setModel(list);
		} catch (Exception e) {
			model.setErrCode("查询失败！");
			logger.info("查询失败", "AccessoryServiceImpl.selectAccessoryList");
		}
		return model;
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	@Override
	public ModelResult<String> save(AccessoryForm form) {

		User user = UserHolder.getUser();
		Accessory accessory = new Accessory();
		accessory.setCreateTime(new Date());
		if (user != null) {
			accessory.setCreator(user.getAccount());
			accessory.setUpdator(user.getAccount());
		}
		accessory.setDescription("");
		accessory.setParentId(form.getParentId());
		accessory.setResourceCode(form.getResourceCode());
		accessory.setResourceDefault("是");
		accessory.setResourceName(form.getResourceName());
		accessory.setResourceType(1);
		accessory.setResourceUrl("/newNode");
		accessory.setSort(form.getSort());
		accessory.setUpdateTime(new Date());

		ModelResult<String> model = new ModelResult<String>();
		try {
			boolean flag = accessoryDao.saveAccessory(accessory);

			if (flag == true) {

				model.setModel(accessory.getId());
			} else {
				model.setErrCode("保存失败！");
			}
		} catch (Exception e) {
			model.setErrCode("保存失败！");
			logger.info("保存失败", "AccessoryServiceImpl.saveAccessory");
		}
		return model;
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	@Override
	public ModelResult<String> update(AccessoryForm form) {
		User user = UserHolder.getUser();
		Accessory accessory = new Accessory();
		accessory.setCreateTime(new Date());
		if (user != null) {
			accessory.setCreator(user.getAccount());
			accessory.setUpdator(user.getAccount());
		}
		accessory.setDescription("");
		accessory.setParentId(form.getParentId());
		accessory.setResourceCode(form.getResourceCode());
		accessory.setResourceDefault("是");
		accessory.setResourceName(form.getResourceName());
		accessory.setResourceType(1);
		accessory.setResourceUrl("/newNode");
		accessory.setSort(form.getSort());
		accessory.setUpdateTime(new Date());
		accessory.setId(form.getId());

		ModelResult<String> model = new ModelResult<String>();
		try {
			boolean flag = accessoryDao.updateAccessory(accessory);
			if (flag == true) {
				model.setModel(accessory.getId());
			} else {
				model.setErrCode("修改失败！");
			}
		} catch (Exception e) {
			model.setErrCode("修改失败！");
			logger.info("修改失败", "AccessoryServiceImpl.updateAccessory");
		}
		return model;
	}

	@Override
	public List<SysResources> selectAccessoryListByCode(String code) {
		return null;
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	@Override
	public ModelResult<Boolean> delete(Accessory accessory) {
		ModelResult<Boolean> modelResult = new ModelResult<Boolean>();
		if (accessory.getId() == null) {
			modelResult.withError("AccessoryServiceImpl.delete", "参数不能为空");
			return modelResult;
		}
		try {
			boolean flag = accessoryDao.deleteAccessory(accessory);
			modelResult.setModel(flag);
			return modelResult;
		} catch (Exception e) {
			logger.error("删除资源失败:", e);
			modelResult.withError("AccessoryServiceImpl.delete", "删除资源失败:" + e.getMessage());
			return modelResult;
		}
	}

	@Override
	public ModelResult<PageResult<Object[]>> findO2oDataListEntityById(String accessoryId) {
		ModelResult<PageResult<Object[]>> model = new ModelResult<PageResult<Object[]>>();
		String sql = "select datalist_no,original_name,creat_or,creat_date from  o2o_datalist where is_delete=? and loanapply_no=? ORDER BY creat_date asc";
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<>(Object[].class, Integer.MAX_VALUE, 0);
		pageQuery.addParam(StatusContexts.O2O_NO);
		pageQuery.addParam(accessoryId);
		pageQuery.setQuerySql(sql);
		try {
			model.setModel(accessoryDao.findDataWithPage(pageQuery));
		} catch (Exception e) {
			model.setErrMsg("附件列表查询失败");
		}
		return model;
	}

	@Override
	public ModelResult<Accessory> findEnTityById(String accessoryId) {
		ModelResult<Accessory> model = new ModelResult<Accessory>();
		try {
			String sql = "select * from o2o_guideline where id=?";
			Accessory accessory = accessoryDao.findEntity(sql, Accessory.class, accessoryId);
			model.setModel(accessory);
		} catch (Exception e) {
			model.setErrMsg("查询资源实体报错");
		}
		return model;
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	@Override
	public ModelResult<Boolean> delFile(String fileId) {
		ModelResult<Boolean> model = new ModelResult<Boolean>();
		try {
			String sql = "update o2o_datalist set is_delete='Y' where datalist_code ='GUIDELINE' and datalist_no = ? ";
			Boolean accessory = accessoryDao.execute(sql, fileId) > 0 ? true : false;
			insertLog(O2oLogType.FILE_STATUS_D, "删除，上传附件,ID:" + fileId);
			model.setModel(accessory);
		} catch (Exception e) {
			model.setErrMsg("删除指南附件失败");
		}
		return model;
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	@Override
	public ModelResult<Boolean> updateFile(String fileId) {
		ModelResult<Boolean> model = new ModelResult<Boolean>();
		try {
			String sql = "update o2o_datalist set urlpath=xx where datalist_code ='GUIDELINE' and datalist_no = ? ";
			Boolean accessory = accessoryDao.execute(sql, fileId) > 0 ? true : false;
			insertLog(O2oLogType.FILE_STATUS_D, "更新，上传附件,ID:" + fileId);
			model.setModel(accessory);
		} catch (Exception e) {
			model.setErrMsg("修改附件失败");
		}
		return model;
	}

	@Override
	public ModelResult<Boolean> findFileByAccessroy(String accessoryId) {
		ModelResult<Boolean> model = new ModelResult<Boolean>();
		try {
			String sql = "select * from  o2o_datalist where is_delete=? and datalist_code ='GUIDELINE' and loanapply_no = ? ";
			List<O2oDataListEntity> list = accessoryDao.findEntitys(sql, O2oDataListEntity.class, StatusContexts.O2O_NO, accessoryId);
			if (list != null && list.size() > 0) {
				model.setModel(false);
			} else {
				model.setModel(true);
			}

		} catch (Exception e) {
			model.setErrMsg("查询指南下的附件失败");
		}
		return model;
	}

	/**
	 * @Title: selectInterviewtitle
	 * @Description: 查询节点标题
	 * @author user
	 * @param typeCode
	 * @return
	 * @return ModelResult<List<Accessory>>
	 * @date 2016年8月10日 下午3:26:37
	 */
	@Override
	public ModelResult<List<Accessory>> selectInterviewtitle(String typeCode) {
		ModelResult<List<Accessory>> model = new ModelResult<List<Accessory>>();
		List<Accessory> list = new ArrayList<>();
		try {
			// 根据指南code查出指南
			Accessory accessory = findAccessoryByResourceCode(typeCode);
			// 根据指南的id查询它的所有子节点

			findChildNode(accessory.getId(), list);

			model.setModel(list);
		} catch (Exception e) {
			model.setErrMsg("数据库操作失败");
		}
		return model;
	}

	@Override
	public ModelResult<List<O2oDataListEntity>> selectInterviewfile(String typeCode) {
		ModelResult<List<O2oDataListEntity>> model = new ModelResult<List<O2oDataListEntity>>();
		List<O2oDataListEntity> list = new ArrayList<>();
		try {
			// 根据指南code查出指南
			Accessory accessory = findAccessoryByResourceCode(typeCode);
			// 根据指南的id查询它的所有子节点
			List<Accessory> result = new ArrayList<Accessory>();

			findChildNode(accessory.getId(), result);

			for (int i = 0; i < result.size(); i++) {
				Accessory acc = result.get(i);
				list.addAll(findFileByAccessroyId(acc.getId()));
			}
			model.setModel(list);
		} catch (Exception e) {
			model.setErrMsg("数据库操作失败");
		}
		return model;
	}

	@Override
	public List<O2oDataListEntity> findFileByAccessroyId(String accessoryId) {
		String sql = "select * from  o2o_datalist where is_delete=? and datalist_code ='GUIDELINE' and loanapply_no = ? ORDER BY creat_date asc";
		List<O2oDataListEntity> list = accessoryDao.findEntitys(sql, O2oDataListEntity.class, StatusContexts.O2O_NO, accessoryId);
		return list;
	}

	public List<Accessory> findChildNode(String id, List<Accessory> result) {
		String sql = "select * from o2o_guideline where parent_id =? ORDER BY  sort";
		List<Accessory> list = accessoryDao.findEntitys(sql, Accessory.class, id);
		if (list != null && list.size() > 0) {
			result.addAll(list);
		}
		return result;
	}

	@Override
	public Accessory findAccessoryByResourceCode(String resourceCode) {
		String sql = "select * from o2o_guideline where resource_code =? ORDER BY  sort";
		Accessory accessory = new Accessory();
		try {
			List<Accessory> list = accessoryDao.findEntitys(sql, Accessory.class, resourceCode);
			if (list != null && list.size() > 0) {
				accessory = list.get(0);
			}
		} catch (Exception e) {
		}
		return accessory;
	}

	@Override
	public ModelResult<List<Accessory>> findNodeByParentId(String parentId) {
		ModelResult<List<Accessory>> modelResult = new ModelResult<>();
		String sql = "select * from o2o_guideline where parent_id =? ORDER BY  sort";
		List<Accessory> list = accessoryDao.findEntitys(sql, Accessory.class, parentId);
		modelResult.setModel(list);
		return modelResult;
	}
	
	/**
	 * @Description: <p> 插入文件修改日志 </p>
	 * @author CXW
	 * @date 2016年9月26日 下午2:35:13
	 * @version V1.0
	 * @param logType 日志类型,updateStr 修改内容
	 * @return void
	 */
	public void insertLog(String logType,String updateStr){
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), logType, null, updateStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<O2oPlatformRegional> getProvinceList() {
		String sql = "SELECT o.regional_name, o.province_code, o.province_name FROM o2o_platform_regional o GROUP BY o.province_name";
		return accessoryDao.findEntitys(sql, O2oPlatformRegional.class);
	}

	@Override
	public String getProvinceByCode(String code) {
		String sql = " SELECT t.province_name FROM( SELECT o.regional_name, o.province_code, o.province_name FROM o2o_platform_regional o GROUP BY o.province_name) t WHERE t.province_code = ? ";
		return accessoryDao.findString(sql, code);
	}

	@Override
	public int saveAccProvince(O2oAccessoryProvince entity) {
		return accessoryDao.insert(entity);
	}

	@Override
	public int deleteAccProvince(String associatedId) {
		String sql = "delete from o2o_accessory_province where associated_id = ?";
		return accessoryDao.execute(sql, associatedId);
	}

	@Override
	public List<String> getSelectProvice(String associatedId) {
		String sql = "select province_code from o2o_accessory_province where associated_id = ?";
		return accessoryDao.findSimpleObjectList(sql, String.class, associatedId);
	}

	@Override
	public String getNoByAssId(String associatedId) {
		String sql = "SELECT loanapply_no FROM o2o_datalist WHERE is_delete = 'N' AND datalist_no = ?";
		return accessoryDao.findString(sql, associatedId);
	}

	@Override
	public ModelResult<PageResult<Object[]>> findO2oDataListEntityByIdNotZB(String accessoryId, List<ActOrgEntity> listPro) {
		ModelResult<PageResult<Object[]>> model = new ModelResult<PageResult<Object[]>>();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT od.datalist_no,od.original_name,od.creat_or,od.creat_date FROM o2o_accessory_province op LEFT JOIN o2o_datalist od ON op.associated_id = od.datalist_no WHERE od.is_delete = 'N' AND op.data_id = ? ");
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<>(Object[].class, Integer.MAX_VALUE, 0);
		pageQuery.addParam(accessoryId);
		try {
			if (listPro.size() == 1) {
				sql.append(" AND op.province_code = ? ");
				pageQuery.addParam(listPro.get(0).getUnitCode());
			} else {// 当list长度大于1时
				sql.append(" AND op.province_code in( ");
				for (int i = 0; i < listPro.size(); i++) {
					sql.append(" ?, ");
					pageQuery.addParam(listPro.get(i).getUnitCode());
				}
				// 删除末尾两个字符, （包括空格 ）
				sql.deleteCharAt(sql.length() - 2);
				sql.append(" ) ");
			}
			pageQuery.setQuerySql(sql.toString());
			model.setModel(accessoryDao.findDataWithPage(pageQuery));
		} catch (Exception e) {
			model.setErrMsg("附件列表查询失败");
		}
		return model;
	}
}
